package controller

import (
	"net/http"
	"time"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/errors"
	"gitee.com/wangshh_123/cross-pay-go/src/middleware"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
	"gitee.com/wangshh_123/cross-pay-go/src/platform/providers/photonpay"
	"gitee.com/wangshh_123/cross-pay-go/src/service"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/auth"
	"gitee.com/wangshh_123/cross-pay-go/src/utils/common"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// StatisticsController 统计控制器
type StatisticsController struct {
	statisticsService *service.StatisticsService
	db                *gorm.DB
}

// NewStatisticsController 创建统计控制器
func NewStatisticsController(client *photonpay.PhotonPayClient) *StatisticsController {
	return &StatisticsController{
		statisticsService: service.NewStatisticsService(client),
		db:                database.DB,
	}
}

// getMatrixAccountFromToken 从token中获取matrixAccount信息
func (c *StatisticsController) getMatrixAccountFromToken(ctx *gin.Context) (string, error) {
	// 从中间件中获取claims
	claims, exists := ctx.Get("claims")
	if !exists {
		return "", errors.NewAppError(http.StatusUnauthorized, "unauthorized", nil)
	}

	// 类型断言
	authClaims, ok := claims.(*auth.Claims)
	if !ok {
		return "", errors.NewAppError(http.StatusInternalServerError, "invalid_token_claims", nil)
	}

	// 从claims中获取用户ID
	userID := authClaims.UserID

	// 首先检查用户是否存在
	var user models.User
	if err := c.db.First(&user, userID).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return "", errors.NewAppError(http.StatusNotFound, "user_not_found", nil)
		}
		return "", errors.NewAppError(http.StatusInternalServerError, "database_error", err)
	}

	// 查询用户的Matrix账户信息
	var matrixAccount models.UserMatrixAccount
	if err := c.db.Where("user_id = ? AND status = 'active'", userID).First(&matrixAccount).Error; err != nil {
		if err == gorm.ErrRecordNotFound {
			return "", errors.NewAppError(http.StatusNotFound, "matrix_account_not_found", nil)
		}
		return "", errors.NewAppError(http.StatusInternalServerError, "database_error", err)
	}

	return matrixAccount.MatrixAccount, nil
}

// GetCardStatistics 获取卡片统计
func (c *StatisticsController) GetCardStatistics(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 获取时间范围参数
	startTimeStr := ctx.Query("start_time")
	endTimeStr := ctx.Query("end_time")

	var startTime, endTime time.Time

	// 如果提供了时间参数，则解析时间
	if startTimeStr != "" {
		parsedStartTime, err := time.Parse("2006-01-02", startTimeStr)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_start_time", err)
			return
		}
		startTime = parsedStartTime
	} else {
		// 如果没有提供开始时间，使用一个很早的时间
		startTime = time.Date(2000, 1, 1, 0, 0, 0, 0, time.Local)
	}

	if endTimeStr != "" {
		parsedEndTime, err := time.Parse("2006-01-02", endTimeStr)
		if err != nil {
			common.Error(ctx, http.StatusBadRequest, "invalid_end_time", err)
			return
		}
		endTime = parsedEndTime
	} else {
		// 如果没有提供结束时间，使用当前时间
		endTime = time.Now()
	}

	// 根据平台类型获取统计数据
	var stats interface{}
	var err error

	switch platformInfo.PlatformType {
	case "photonpay":
		// 获取PhotonPay的matrixAccount
		matrixAccount, err := c.getMatrixAccountFromToken(ctx)
		if err != nil {
			common.Error(ctx, http.StatusUnauthorized, "get_matrix_account_failed", err)
			return
		}
		stats, err = c.statisticsService.GetCardStatistics(ctx.Request.Context(), startTime, endTime, matrixAccount)
	case "hlpay":
		// 获取HlPay的统计数据
		stats, err = c.statisticsService.GetHlPayCardStatistics(ctx.Request.Context(), startTime, endTime, platformInfo)
	default:
		common.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_card_statistics_failed", err)
		return
	}

	common.Success(ctx, stats)
}

// GetHlPayEnhancedStatistics 获取HlPay增强统计数据
func (c *StatisticsController) GetHlPayEnhancedStatistics(ctx *gin.Context) {
	// 从中间件获取平台信息
	platformInfo, exists := middleware.GetPlatformInfoFromContext(ctx)
	if !exists {
		common.Error(ctx, http.StatusUnauthorized, "platform_info_not_found", nil)
		return
	}

	// 验证平台类型
	if platformInfo.PlatformType != "hlpay" {
		common.Error(ctx, http.StatusBadRequest, "unsupported_platform", nil)
		return
	}

	// 获取增强统计数据
	stats, err := c.statisticsService.GetHlPayEnhancedStatistics(ctx.Request.Context(), platformInfo)
	if err != nil {
		common.Error(ctx, http.StatusInternalServerError, "get_hlpay_enhanced_statistics_failed", err)
		return
	}

	common.Success(ctx, stats)
}
